import React, { Component, PropTypes } from "react";
import ReactDOM from "react-dom";
import Clipboard from "clipboard";
import wx from "wx";

import AJAX from "../../lib/ajax";
import Tools from "../../lib/tools";
import Dialog from "../MyPackage/components/Dialog";
import Toast from "../MyPackage/components/Toast";
import AdBlock from "../../components/AdBlock"
import { addErrorListener } from "../../lib/handleError"

import weixinShare from "../../lib/weixinShare";

require('../../lib/rem');
require('../../styles/common.less');
require('../../styles/lux.less');
require('../../styles/resetWeui.less');
require('./OpenBoxFinal.less');

class OpenBoxSuccess extends Component {
    constructor(props) {
        super(props);
        this.state = {
            order_id: Tools.getParams().order_id,
            time60: 60,     //60s倒计时
            isTime60Over: false,     // 60s倒计时结束
            btnStateText: '再次开箱（60s）',
            openBoxState: 1,    //再次开箱状态    0:开箱成功启用再次开箱        1:开箱失败启用一健开箱
            time: 10,//10秒倒计时
            isContact: false,//是否联系客服
            isTimeOver: false,//10s倒计时结束
            isShowDetail: false,//是否展示收费详情
            data: {
                addr: '',
                code: '',
                exp_name: '',
                exp_code: '',
                cell_desc: '',
                settle_amount: '',//取件费用,
                basic_amount: '',//基础费用
                delay_amount: '',//延期费用
                contact_phone: '',//客服电话
            },
            openStateDesc: '开箱中请稍后',  //开箱状态  0:失败  1:成功   2:开箱中
            openState: 2,  //开箱状态  0:失败   1:成功   2:开箱中
            isLoading: true,
            rule: '',
            to_pickup_count: 0, //待取件数量
            exp_code: "", //快递单号
            balance: "", //账户余额
            openSuccess: false,
            showCostDetail: false,
        };
    }

    componentWillMount() {
        addErrorListener()()

        //获取订单详情 并开箱
        this.getOrderDetail();
    }

    componentDidMount() {
        new Clipboard('.icon-copy');
        AJAX.appendBaiduAnalysis();

        //    获取微信权限，为关闭窗口请求做准备
        AJAX.request('get_signature', {
            full_url: window.location.href
        }, (data) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ["closeWindow", "hideAllNonBaseMenuItem"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(() => {
                //隐藏分享功能
                wx.hideAllNonBaseMenuItem()
            })
        })
        new Clipboard(".btn")
    }

    polling = timestamp => {
        const now = Date.parse(new Date());
        const diff = (now - timestamp) / 1000;
        // 设置 15秒超时
        if (diff > 15) {
            this.openBoxFail();
            return;
        };

        const { order_id } = this.state;
        AJAX.request('pickup_result_polling', { order_id }, (data) => {
            if (data.code === 0 && data.body.is_pickup) {
                this.openBoxSuccess(data);
            } else {
                setTimeout(() => {
                    this.polling(timestamp);
                }, 1000)
            }
        })
    }

    openboxPending = () => {
        this.setState({
            openState: 2,
            openStateDesc: "开箱中请稍后..."
        })
    }

    openBoxSuccess = result => {
        const { time60, data } = this.state;
        this.setState({
            openSuccess: true,
            openState: 1,
            openStateDesc: data.cell_desc + '箱门打开成功',
            to_pickup_count: result.body.to_pickup_count, //待取件数量
        })
        if (time60 === 60) {
            this.timer60 = setInterval(this.setTime60, 1000)
        }
        var type = 6;
        var advert_url = '';

        // 只有当 待取件 为0时，再跳转广告
        if (result.body.to_pickup_count < 1) {
            AJAX.request('get_advert_detail', { type }, (data) => {
                this.fetchSaveAdvert(data.body.id, 4);
                if (data.code == 0) {
                    advert_url = data.body.url;
                    window.location.href = advert_url;
                }
            })
        }
    }

    /**
     * 
     * @param {*} advertId 广告id
     * @param {*} type 2: 点击; 3: 曝光; 4: 跳转;
     */
     fetchSaveAdvert(advertId, type) {
        const params = {
            advertId: advertId,
            type: type,
        };
        AJAX.request('advertSave', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
    }

    openBoxFail = () => {
        const { time60 } = this.state;
        this.setState({
            openState: 0, //开箱状态，0:失败，1:成功，2:开箱中，3:网络断开
            openStateDesc: '箱门打开失败',
            to_pickup_count: 0,
            balance: 0,
            show_reward: false,
        })
        if (time60 === 60) {
            this.timer60 = setInterval(this.setTime60, 1000)
        }
    }

    openBoxNetworkFail = () => {
        const { time60 } = this.state;
        this.setState({
            openState: 3,
            openStateDesc: '柜体网络断开',
            to_pickup_count: 0,
            balance: 0,
            show_reward: false,
        })

        if (time60 === 60) {
            this.timer60 = setInterval(this.setTime60, 1000)
        }
    }

    reopenBoxSuccess = () => {
        this.setState({
            openState: 1,
            openStateDesc: '箱门已打开',
        })
    }

    reopenBoxNetworkFail = () => {
        this.setState({
            openState: 3,
            openStateDesc: '',
        })
    }

    reopenBoxFail = () => {
        this.setState({
            openState: 0, //开箱状态，0:失败，1:成功，2:开箱中，3:网络断开
            openStateDesc: '箱门打开失败',
        })
    }

    //60秒倒计时
    setTime60 = () => {
        if (this.state.time60 === 1) {
            this.setState({
                time60: 0,
            })
            clearInterval(this.timer60);//清空定时器
            return
        } else {
            let time60 = this.state.time60 - 1
            this.setState({
                time60,
                btnStateText: `再次开箱（${time60}s）`
            })
        }
    }

    //获取订单详情
    getOrderDetail = () => {
        const { order_id } = this.state;
        AJAX.request('order_detail', { order_id }, (data) => {
            if (data.code === 0) {
                const dataBody = data.body || {};
                const storage_info = dataBody.storage_info || {};
                let copyData = {
                    type: storage_info.type,
                    addr: storage_info.addr,
                    code: storage_info.code,
                    cell_desc: storage_info.cell_desc,
                    exp_name: dataBody.exp_name,
                    exp_code: dataBody.exp_code,
                    settle_amount: (dataBody.settle_amount / 100).toFixed(2), // 取件费用,
                    basic_amount: (dataBody.basic_amount / 100).toFixed(2), // 基础费用
                    delay_amount: (dataBody.delay_amount / 100).toFixed(2), // 延期费用
                    balance: (dataBody.balance / 100).toFixed(2),//账户余额
                    contact_phone: dataBody.contact_phone,
                };

                this.setState({
                    data: copyData,
                    balance: copyData.balance,
                    exp_code: dataBody.exp_code, //快递单号
                    isLoading: false,
                    open_code: dataBody.open_code,
                })

                this.openBox();
            }
        });
    }

    //点击再次开箱
    clickOpenBoxAgain = () => {
        const { openState, time60, tap_time, openSuccess } = this.state
        //在点击过开箱的情况下，两次开箱间隔小于十秒
        const disable_open = tap_time > 0 && tap_time - time60 < 10 //10秒之内不能点击下一次
        if (openState === 2 || disable_open) {
            Toast.warn({ content: "请稍后再试" });
            return;
        }
        if (openState === 1) {          //开箱成功调用再次开箱
            this.openBoxAgain();
        }
        if (openState === 0 || openState === 3) {    //开箱失败或者网络断开调用一键开箱
            if (openSuccess) {
                // 曾经开箱成功过，所以调用再次开箱
                this.openBoxAgain();
            } else {
                this.openBox(true)
            }
        }
        this.setState({
            tap_time: time60
        })
    }

    //pickup 一键开箱
    /**
     * @param  {boolean} again 再次调用 pickup 一键开箱
     */
    openBox = again => {
        const { order_id } = this.state;
        this.openboxPending();
        AJAX.request('pickup_async_open', { order_id }, (data) => {
            const { code } = data;
            if (code === 0) {
                // 发送开箱指令成功
                const now = Date.parse(new Date());
                this.polling(now);
            } else if (
                code === 40000 || //"路由不存在"
                code === 40001 || //"客户端不活跃"
                code === 40002 || //"客户端已断开"
                code === 40003  //"Broker通讯错误"
            ) {
                this.openBoxNetworkFail();
            } else if (again && code === 15119) { // 订单已取走
                this.openBoxAgain();
            } else {
                this.openBoxFail();
            }
        })
    }

    //再次开箱
    openBoxAgain = () => {
        const { order_id } = this.state;

        this.openboxPending();

        AJAX.request('pickup_sync_reopen', { order_id }, (data) => {
            if (data.code === 0) {
                this.reopenBoxSuccess();
            } else if (
                data.code === 40000 || //"路由不存在"
                data.code === 40001 || //"客户端不活跃"
                data.code === 40002 || //"客户端已断开"
                data.code === 40003  //"Broker通讯错误"
            ) {
                this.reopenBoxNetworkFail();
            } else {
                this.reopenBoxFail();
            }
        })
    }

    // 联系客服
    handleStatLine = () => {
        let content = `您的订单编号为：${this.state.exp_code}。建议您复制此编号，并点击【确认】跳转至聊天界面联系客服。`
        if (Clipboard.isSupported()) {
            content = "点击【确认】后将自动复制订单信息，并跳转至公众号聊天界面。"
        }
        Dialog.confirm({
            title: "",
            content,
            okText: "确认",
            cancelText: "取消",
            onOK: () => {
                this.refs.btn.click()
                wx.closeWindow()
            },
        })
        AJAX.request('stat_hotline', {}, (data) => { })
    }

    //继续取下一件
    jumpToHome = () => {
        const { openState } = this.state
        if (openState === 2) {
            Toast.warn({ content: '请稍后再试' });
            return
        } else {
            const wx_type = window.localStorage.getItem('wx_type');
            window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
        }
    }

    //清空定时器
    componentWillUnmount() {
        clearInterval(this.timer60);      //60秒定时
    }

    createOpenErrorElem = () => {
        return (
            <div className="open-tip">
                <div>1.请尝试轻拍箱门，并再次点击「再次开箱」。</div>
                <div>2.请前往柜体屏幕前，通过密码取件。</div>
                <div>3.多次「再次开箱」无果，请点击「联系客服」。</div>
            </div>
        )
    }

    createOpenLogEmel(contact_phone) {
        return (
            <div className="open-tip">
                <div>1.请前往柜体屏幕前，通过密码取件。</div>
                <div>2.请联系物流中心，服务电话：<span>{contact_phone}</span></div>
            </div>
        )
    }

    createFooterElem = () => {
        const { time60, btnStateText, openState, to_pickup_count, } = this.state
        const show_reopen = time60 > 0 && openState != 2;
        const show_contact = (time60 <= 0 && openState === 1) || (openState === 0 || openState === 3)    //取件成功时需要读秒为0才显示
        const show_next = openState === 1 && to_pickup_count > 0;     //取件成功且有下一件

        if (!show_reopen && !show_contact && !show_next) return null;

        return (
            <div className="footer-box">
                <div className="footer-btn-box">
                    {
                        show_reopen && (
                            <button
                                className={(show_contact || show_next) ? 'footer-btn2' : 'footer-btn'}
                                onClick={this.clickOpenBoxAgain}
                            >
                                {btnStateText}
                            </button>
                        )
                    }
                    {
                        show_contact && (
                            <button
                                className={show_next ? 'footer-btn2' : 'footer-btn'}
                                onClick={this.handleStatLine}
                            >
                                联系客服
                            </button>
                        )
                    }
                    {
                        show_next && (
                            <button
                                className="footer-btn"
                                onClick={this.jumpToHome}
                            >
                                <span>继续取下一件</span>
                                <span style={{ position: "relative" }}>
                                    <span className="red_num_dot">{to_pickup_count}</span>
                                </span>
                            </button>
                        )
                    }
                </div>
            </div>
        )
    }

    render() {
        const {
            exp_code,
            isLoading,
            openState,
            openStateDesc,
            data,
            showCostDetail,
        } = this.state;

        if (isLoading) return null;

        const text = `订单号：${exp_code}`
        const show_open_error = openState === 0;             //开箱失败
        const show_open_lag = openState === 3;               //开箱失败，网络错误

        const dataList = [
            { label: '存放位置', value: data.addr },
            { label: '柜体编号', value: data.code },
            { label: data.exp_name, value: data.exp_code },
            {
                label: '取件费用', value: data.settle_amount + '元',
                children: [
                    { label: '基础费用', value: data.basic_amount },
                    { label: '延期费用', value: data.delay_amount },
                ],
            },
        ];

        return (
            <div className="page">
                <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb10">
                    <div className="openBox">
                        <div className="openMain">
                            {openState == 1 && <img className="success" src={'https://wechat.jinlb.cn/assets/images/open-success.png'} alt="" />}
                            {openState == 0 && <img className="failure" src={'https://wechat.jinlb.cn/assets/images/open-failure.png'} alt="" />}
                            {openState == 2 && <img className="waiting" src={'https://wechat.jinlb.cn/assets/images/open-waiting.png'} alt="" />}
                            {openState == 3 && <img className="network" src={'http://wechat.jinlb.cn/assets/images/open-network.png'} alt="" />}
                            <div><p className="info">{openStateDesc}</p></div>
                        </div>

                        {show_open_error && this.createOpenErrorElem()}

                        {show_open_lag && this.createOpenLogEmel(data.contact_phone)}

                        <AdBlock type="6" />
                    </div>

                    <div className="expressDetailBox lux-mt10">
                        {
                            dataList.map((item, index) => (
                                <div>
                                    <div className="lux-d-f lux-ai-c lux-pt10 lux-pb10" style={{ borderBottom: index !== dataList.length - 1 ? '1px solid rgba(238,238,238,1)' : '' }}>
                                        <div className="lux-c999 lux-fz14 lux-fw-500 lux-miw80">{item.label}:</div>
                                        {
                                            index === 2 && (
                                                <div className="lux-flex-1 lux-d-f lux-ai-c">
                                                    <div className="lux-c333 lux-fz14 lux-fw-500">{item.value}</div>
                                                    <img
                                                        className="icon-copy lux-ml20"
                                                        src="https://wechat.jinlb.cn/assets/images/icon-copy.png"
                                                        data-clipboard-text={item.value}
                                                        onClick={() => Toast.success({ content: '复制成功' })}
                                                    />
                                                </div>
                                            )
                                        }
                                        {
                                            item.label === '取件费用' && (
                                                <div className="lux-flex-1 lux-d-f lux-jc-sb">
                                                    <div className="lux-cfe763e lux-fz14 lux-fw-500">{item.value}</div>
                                                    {
                                                        !data.out_time && (
                                                            <div
                                                                className="lux-ca9a9a9 lux-fz14 lux-fw-500"
                                                                onClick={() => this.setState({ showCostDetail: !showCostDetail })}
                                                            >
                                费用明细 >
                                                            </div>
                                                        )
                                                    }
                                                </div>
                                            )
                                        }

                                        {
                                            index !== 2 && !['取件费用'].includes(item.label) && (
                                                <div className="lux-c333 lux-fz14 lux-fw-500">{item.value}</div>
                                            )
                                        }
                                    </div>
                                    {
                                        showCostDetail && item.children && (
                                            <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb10 lux-bottom-line">
                                                {
                                                    item.children.map(subItem => (
                                                        <div className="lux-flex-1 lux-d-f lux-jc-sb">
                                                            <div className="lux-c999 lux-fz14 lux-fw-500">{subItem.label}</div>
                                                            <div className="lux-cfe763e lux-fz14 lux-fw-500">{subItem.value}</div>
                                                        </div>
                                                    ))
                                                }
                                            </div>
                                        )
                                    }
                                </div>
                            ))
                        }
                    </div>

                    <button ref="btn" className="btn lux-none" data-clipboard-text={text}>复制</button>
                </div>

                {this.createFooterElem()}
            </div>
        );
    }
}

ReactDOM.render(<OpenBoxSuccess />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}

